package com.qms.tubu.fragment.date;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.qms.tubu.R;
import com.qms.tubu.activity.MainActivity;
import com.qms.tubu.activity.MultiPhotoActivity;
import com.qms.tubu.adapter.DateAdapter;
import com.qms.tubu.adapter.LoadMoreAdapter;
import com.qms.tubu.bean.DateBean;
import com.qms.tubu.dialog.ExPopupWindow;
import com.qms.tubu.fragment.BaseFragment;
import com.qms.tubu.tools.UrlConfig;
import com.qms.tubu.widget.LoadMoreRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import tool.lib.ToastTool;
import tool.lib.volley.ExErrorListener;
import tool.lib.volley.ExListener;
import tool.lib.volley.JsonRequest;
import tool.lib.volley.VolleyTool;

/**
 * Created by Mad on 2015/7/2.
 */
public class DateFragment extends BaseFragment implements View.OnClickListener,
        RadioGroup.OnCheckedChangeListener,SwipeRefreshLayout.OnRefreshListener,
        LoadMoreAdapter.OnItemClickListener,LoadMoreRecyclerView.OnLoadMoreListener{
    private SwipeRefreshLayout mRefreshLayout;
    private LoadMoreRecyclerView mDateRecycler;
    private LinearLayoutManager mLayoutManager;
    private DateAdapter mAdapter;
    private MainActivity mActivity;
    private TextView mFilterText;
    private String mArea;
    private int mSex;
    private int mPage;
    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.fragment_date,container,false);
        mRefreshLayout=(SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        mDateRecycler=(LoadMoreRecyclerView) rootView.findViewById(R.id.date_recycler_view);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLayoutManager=new LinearLayoutManager(rootView.getContext(),LinearLayoutManager.VERTICAL,false);
        mDateRecycler.setLayoutManager(mLayoutManager);
        mDateRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = 0;
                outRect.left = 0;
                if (parent.getChildAdapterPosition(view) >= parent.getAdapter().getItemCount() - 2)
                    outRect.bottom = 0;
                else
                    outRect.bottom = getResources().getDimensionPixelOffset(R.dimen.date_item_driver_size);
                outRect.right = 0;
            }
        });
        mDateRecycler.setOnLoadMoreListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        mArea="Nearby";
        mSex=0;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity= (MainActivity) getActivity();
        mFilterText= (TextView) mActivity.getDateSpinner().findViewById(R.id.date_filter_text);
        updateFilterText();
        mActivity.getDateSpinner().setOnClickListener(this);
        rootView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.setRefreshing(true);
                refreshDate();
            }
        }, getResources().getInteger(R.integer.first_refresh_delay_time));

    }
    private void refreshDate()
    {
        if(mArea.equals("Nearby") && mActivity.getLocation()==null)
        {
            ToastTool.showToast(getResources().getString(R.string.location_not_find_error_text));
            mRefreshLayout.setRefreshing(false);
            return;
        }
        requestDate(true,new ExListener(){
            @Override
            public void onResponse(JSONObject object) {
                super.onResponse(object);
                mRefreshLayout.setRefreshing(false);
                if(verifyResult.getResult()==0)
                {
                    try {
                        List<DateBean> list= JSON.parseArray(object.getString("publish"),DateBean.class);
                        if(mAdapter==null)
                        {
                            mAdapter=new DateAdapter(getActivity());
                            mAdapter.setOnItemClickListener(DateFragment.this);
                            mDateRecycler.setAdapter(mAdapter);
                            mAdapter.getList().addAll(list);
                            mAdapter.notifyDataSetChanged();
                        }
                        else
                        {
                            mAdapter.getList().clear();
                            mAdapter.getList().addAll(list);
                            mAdapter.notifyDataSetChanged();
                        }
                        mDateRecycler.loadComplete(list.size());
                        mPage=1;
                        return;
                    } catch (JSONException e) {
                        verifyResult.setResult(PARSE_ERROR);
                    }
                }
                else if(verifyResult.getResult()==-1) {
                    if (mAdapter == null) {
                        mAdapter = new DateAdapter(getActivity());
                        mAdapter.setOnItemClickListener(DateFragment.this);
                        mDateRecycler.setAdapter(mAdapter);
                    } else {
                        mAdapter.getList().clear();
                        mAdapter.notifyDataSetChanged();
                    }
                    mDateRecycler.loadComplete(0);
                    mPage = 1;
                    return;
                }
                ToastTool.showToast(verifyResult.getMsg());
            }
        },new ExErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                mRefreshLayout.setRefreshing(false);
            }
        });
    }
    private void requestDate(boolean isRefresh,ExListener listener,ExErrorListener errorListener)
    {
        JsonRequest request=new JsonRequest(UrlConfig.getUrl(R.string.main_date_url),listener,errorListener);
        request.setTag(DateFragment.class);
        if(isRefresh)
            request.put("page","0");
        else
            request.put("page",String.valueOf(mPage));
        if(mArea.equals("Nearby"))
        {
            request.put("longitude",String.valueOf(mActivity.getLocation().getLongitude()));
            request.put("latitude",String.valueOf(mActivity.getLocation().getLatitude()));
        }
        if(getTubuApplication().getAccount()!=null)
            request.put("aid",getTubuApplication().getAccount().getId());
        request.put("sex", String.valueOf(mSex));
        request.setTag(DateFragment.this);
        VolleyTool.getInstance().add(request);
    }
    @Override
    public void onRefresh() {
        refreshDate();
    }

    private void updateFilterText()
    {
        StringBuilder builder=new StringBuilder();
        if(mArea.equals("All"))
            builder.append("全国");
        else
            builder.append("附近");
        builder.append("·");
        switch (mSex)
        {
            case 0:
                builder.append("全部");
                break;
            case 1:
                builder.append("男生");
                break;
            case 2:
                builder.append("女生");
                break;
        }
        mFilterText.setText(builder.toString());

    }

    @Override
    public void onLoadMore() {
        ToastTool.showToast("尚未实现");
    }

    @Override
    public void onItemClick(View view, int position, long itemId) {

    }

    private String mTempArea;
    private int mTempSex;
    @Override
    public void onClick(View v) {
        View popupView=mActivity.getLayoutInflater().inflate(R.layout.date_spinner_popup, null);
        final ExPopupWindow popupWindow=new ExPopupWindow(popupView);
        RadioGroup areaGroup=(RadioGroup) popupView.findViewById(R.id.date_area_group);
        mTempArea=mArea;
        if(mArea.equals("All"))
            areaGroup.check(R.id.nationwide_radio_btn);
        else
            areaGroup.check(R.id.nearby_radio_btn);
        RadioGroup sexGroup=(RadioGroup) popupView.findViewById(R.id.date_sex_group);
        mTempSex=mSex;
        switch (mSex)
        {
            case 0:
                sexGroup.check(R.id.all_radio_btn);
                break;
            case 1:
                sexGroup.check(R.id.man_radio_btn);
                break;
            case 2:
                sexGroup.check(R.id.women_radio_btn);
                break;
        }
        areaGroup.setOnCheckedChangeListener(this);
        sexGroup.setOnCheckedChangeListener(this);
        popupView.findViewById(R.id.popup_cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupView.findViewById(R.id.popup_commit_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!mTempArea.equals(mArea) || mTempSex!=mSex)
                {
                    mArea=mTempArea;
                    mSex=mTempSex;
                    updateFilterText();
                    mRefreshLayout.setRefreshing(true);
                    refreshDate();
                }
                popupWindow.dismiss();
            }
        });
        PopupWindowCompat.showAsDropDown(popupWindow, mActivity.getToolbar(), 0, 0, Gravity.NO_GRAVITY);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId)
        {
            case R.id.nationwide_radio_btn:
                mTempArea="All";
                break;
            case R.id.nearby_radio_btn:
                mTempArea="Nearby";
                break;
            case R.id.all_radio_btn:
                mTempSex=0;
                break;
            case R.id.man_radio_btn:
                mTempSex=1;
                break;
            case R.id.women_radio_btn:
                mTempSex=2;
                break;
        }
    }
}
